<?php

namespace app\base\controller\api;

use app\base\service\MemberService;
use app\base\service\PaymentService;
use think\admin\Controller;
use app\base\model\MemberPlans;
use app\base\controller\api\Auth;
use app\base\model\MemberBeanPackages;
use app\base\model\MemberOrder as MemberOrderMod;
use think\admin\extend\CodeExtend;


/**
 * 会员用户订单
 * Class MemberShip
 * @package app\base\api\controller
 */
class MemberOrder extends Auth
{
   // private $user_id=10002;
    //订单创建
    public function createOrder()
    {
       $data = $this->app->request->post();
       $this->_vali([
           'id.require'  => '套餐ID不能为空！',
           'num.require'  => '数量不能为空！',
           'type.require'  => '类型不能为空！'
           ],$data);
       $order_id = MemberService::instance()->createOrder($this->user_id,$data['id'],$data['num'],$data['type'],1);
       if(empty($order_id)) $this->error('订单创建失败');
       $pay_info = MemberService::instance()->createWxPay($order_id);
       if($pay_info['code']){
           $this->success('订单创建成功',$pay_info['data']);
       }else{
           $this->error($pay_info['info']);
       }

    }

    //订单查询
    public function getOrderInfo()
    {
        $id = input('id');
        $order = MemberOrderMod::mQuery()->where(['id'=>$id])->find();
        if(empty($order)) $this->error('订单不存在');
        $order['content'] = json_decode($order['content'],true);

        $this->success('查询成功',$order);
    }
    //订单状态查询
    public function getOrderStatus(){
        $id = input('id');
        //查询订单是否支付
        $order_info = MemberOrderMod::mQuery()->where(['id'=>$id])->find();
        $status = $order_info['status'];
        if($status==2){
            //订单已支付,发放订单内容
            MemberService::instance()->payOrderContent($id);
            $this->success('查询成功',2);
        }else{
            $result = PaymentService::query($order_info['order_no']);
            if (isset($result['trade_state']) && $result['trade_state'] === 'SUCCESS') {
                MemberOrderMod::mQuery()->where(['id'=>$id])->update(['status'=>2,'pay_date'=>date('Y-m-d H:i:s')]);
                MemberService::instance()->payOrderContent($id);
                $this->success('查询成功',2);
            }else{
                $this->success('查询成功',1);
            }
        }
        //测试定时发放
        //MemberService::instance()->cronIssueBeans();
        $this->success('查询成功',$status);
    }

    //订单列表
    public function getOrderList(){
        $page= input('page',1);
         $page_size = input('page_size',20);
        $list = MemberOrderMod::mQuery()->where(['user_id'=>$this->user_id])->order('id desc')
            ->page($page,false,false,$page_size);
        foreach ($list['list'] as &$v){
            $v['content'] = json_decode($v['content'],true);
        }
        $this->success('获取成功', $list);

    }



}
